<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工号" prop="teacherid">
        <el-input v-model="queryParams.teacherid" placeholder="请输入工号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入昵称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所教年份" prop="yearAdmission">
        <el-input v-model="queryParams.yearAdmission" placeholder="请输入年份" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所在学校" prop="yearAdmission">
        <el-select v-model="queryParams.school" placeholder="请输入班级" clearable>
          <el-option v-for="item in school_name" :key="item.value" :label="item.label" :value="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['teacher:teacher:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['teacher:teacher:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['teacher:teacher:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['teacher:teacher:export']">导出</el-button>
        <el-button type="warning" plain icon="upload" @click="handleImport"
          v-hasPermi="['teacher:teacher:add']">导入</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="80" />
      <el-table-column label="工号" align="center" prop="teacherid" />
      <el-table-column label="老师姓名" align="center" prop="username" />
      <el-table-column label="班级" align="center" prop="classss" />
      <el-table-column label="所教年级" align="center" prop="yearAdmission" />
      <el-table-column label="学校" align="center" prop="school" />
      <el-table-column label="教导主任id" align="center" prop="deanId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['teacher:teacher:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['teacher:teacher:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改教师管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="teacherRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工号" prop="teacherid">
          <el-input v-model="form.teacherid" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="老师姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="班级" prop="classss">
          <el-select v-model="form.classss" placeholder="请输入班级" clearable>
            <el-option v-for="item in class_name" :key="item.value" :label="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所教年份" prop="grade">
          <el-input v-model="form.yearAdmission" placeholder="请输入入学年份" />
        </el-form-item>
        <el-form-item label="学校" prop="school">
          <el-select v-model="form.school" placeholder="请选择学校" clearable>
            <el-option v-for="item in school_name" :key="item.value" :label="item.label"
              :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <span>新增教师密码统一设置为123456</span>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传文件 -->
    <el-dialog title="上传文件" v-model="excelopen" width="400px" append-to-body>
      <el-upload ref="uploadRef" class="upload-demo" :action="uploadImgUrl" :headers="headers"
        :on-error="handleUploadError" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload"
        :auto-upload="false">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">
          上传文件
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            只能上传xlx文件
          </div>
        </template>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script setup name="Teacher">
import { listTeacher, getTeacher, delTeacher, addTeacher, updateTeacher } from "@/api/teacher/teacher";
import UploadUtils from '@/utils/UploadUtils';
const { proxy } = getCurrentInstance();
import { getToken } from "@/utils/auth";
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/teacher/teacher/importData");
const headers = ref({ Authorization: "Bearer " + getToken() });
const teacherList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const { class_name, school_name } = proxy.useDict('class_name', 'school_name');
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    teacherid: null,
    username: null,
    deanId: null
  },
  rules: {
    teacherid: [
      { required: true, message: "工号不能为空", trigger: "blur" }
    ],
    username: [
      { required: true, message: "昵称不能为空", trigger: "blur" }
    ],
    school: [
      { required: true, message: "学校不能为空", trigger: "blur" }
    ],
    classss: [
      { required: true, message: "班级不能为空", trigger: "blur" }
    ],
    yearAdmission: [
      { required: true, message: "入学年份不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询教师管理列表 */
function getList() {
  loading.value = true;
  listTeacher(queryParams.value).then(response => {
    teacherList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {}
  form.value = {
    id: null,
    teacherid: null,
    username: null,
    password: null,
    school: null,
    grade: null,
    yearAdmission: null,
    classss: null,
    deanId: null
  };
  proxy.resetForm("teacherRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {}
  proxy.resetForm("queryRef");
  fetchInfo()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加教师管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTeacher(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改教师管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["teacherRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTeacher(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.password = '123456';
        addTeacher(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除教师管理编号为"' + _ids + '"的数据项？').then(function () {
    return delTeacher(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('teacher/teacher/export', {
    ...queryParams.value
  }, `teacher_${new Date().getTime()}.xlsx`)
}



// 文件上传导入
// 学生信息导入功能 导入excel
const props = defineProps({
  modelValue: [String, Object, Array],
  fileSize: {
    type: Number,
    default: 1,
  },
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  }
});
const { excelopen, uploadRef, handleImport, submitUpload, handleUploadError, handleBeforeUpload, handleUploadSuccess } = UploadUtils(props, proxy, getList);
import { getInfo } from '@/api/login'
const infoName = ref({})
// 获取当前用户信息
async function fetchInfo() {
  try {
    const result = await getInfo(); // 等待函数解析完成   
    if (result.roles[0] == "admin") {
      infoName.value.type = 0
      getList();
    } else if (result.roles[0] == 'seniormanage') {
      infoName.value.userName = result.user.userName;
      infoName.value.deptId = result.user.deptId;
      infoName.value.userId = result.user.userId
      infoName.value.type = 1
      getListBySeniormanage()
    }

  } catch (error) {
    console.error(error);
  }
}
fetchInfo()

function getListBySeniormanage() {
  loading.value = false;
  console.log(infoName.value);
  queryParams.value.deanId = infoName.value.userId
  listTeacher(queryParams.value).then(response => {
    teacherList.value = response.rows;
    total.value = response.total;
    loading.value = false;

  })

}
</script>
